package com.st.event.demo.register;

import com.st.event.demo.annotation.EventScan;
import com.st.event.demo.scanner.EventListenerRegistryScanner;
import com.st.event.demo.source.EventAttributeSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class EventListenerDefinitionRegister implements ImportBeanDefinitionRegistrar {

    @Autowired
    private ApplicationContext ac;
    @Autowired
    private EventAttributeSource eventAttributeSource;

    /**
     * 同步扫描包方式 注入ioc
     * @param importingClassMetadata
     * @param registry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        System.out.println("执行2-----------");
        // 扫描注解内的信息
        AnnotationAttributes scanAttrs = AnnotationAttributes.fromMap(importingClassMetadata
                .getAnnotationAttributes(EventScan.class.getName()));
        Map<String, Object> annotationAttributes = importingClassMetadata
                .getAnnotationAttributes(EventScan.class.getName());
        String[] basePackages = scanAttrs.getStringArray("basePackage");
        System.out.println(basePackages.toString());

        if (scanAttrs != null) {
            registerBeanDefinitions(scanAttrs, registry);
        }
    }

    void registerBeanDefinitions(AnnotationAttributes scanAttrs, BeanDefinitionRegistry registry) {
        List<String> basePackages = Arrays.stream(scanAttrs.getStringArray("basePackage"))
                .filter(StringUtils::hasText).collect(Collectors.toList());
        System.out.println("执行3-----------");
        EventListenerRegistryScanner scanner = new EventListenerRegistryScanner(registry);
        scanner.setAc(ac);
        scanner.setEventAttributeSource(eventAttributeSource);
        scanner.registerFilters();
        scanner.scan(StringUtils.toStringArray(basePackages));
    }



}
